package com.daji.reference;

import com.daji.pojo.SubUser;
import com.daji.pojo.User;
import org.springframework.beans.BeanUtils;

/*
* 测试Java的深拷贝和浅拷贝
* */
public class DeepCopy {
    public static void main(String[] args) {
        //shallowCopy();
        deepCopy();
    }
    //浅拷贝
    //该案例说明，浅copy 不管对普通类型还是引用类型(SubUser)都是一视同仁地浅
    private static void shallowCopy(){
        User user0 = new User("lbw", "123", 12, new SubUser("sn"));
        System.out.println(user0);
        System.out.println("浅拷贝开始");
        User user1 = user0;
        user1.setUserName("lbw-copy");
        user1.setSubUser(new SubUser("sn-copy"));
        System.out.println(user0);
    }
    //深拷贝（复制每个属性的方式）
    //序列化反序列化方式试过了，是成功的.
    //逐个属性赋值的方式也是成功的。这也是一种深拷贝
    private static void deepCopy(){
        SubUser subUser = new SubUser("sn");
        User user0 = new User("lbw", "123", 12, subUser);
        User user1  = new User();
        System.out.println("深拷贝开始");
        BeanUtils.copyProperties(user0,user1);
        System.out.println(user0);
        System.out.println(user1);
        System.out.println("现在修改user1的值，看看user0会不会被影响");
        user1.setUserName("lbw-copy");
        user1.setSubUser(new SubUser("sn-copy"));
        System.out.println("user1："+user1);
        System.out.println("user0："+user0);
    }
}


